//
//  WebViewController.m
//  TaoBaoKe
//
//  Created by 王冬 on 2020/7/15.
//  Copyright © 2020 王冬. All rights reserved.
//

#import "WebViewController.h"
#import <WebKit/WebKit.h>
@interface WebViewController ()<WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic, strong) UIProgressView    *progressView;
@property (nonatomic, copy) NSString *fileUrl;
@property (nonatomic, copy) NSString *footUrl;
@property (nonatomic, copy) NSString *headerString;
@property (nonatomic, strong) UIView *footView;
@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.titleStr;
   self.webView = [[WKWebView alloc] init];
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

             WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
             WKUserContentController *wkUController = [[WKUserContentController alloc] init];
             [wkUController addUserScript:wkUScript];

             WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
             wkWebConfig.userContentController = wkUController;
 
             [wkWebConfig.userContentController addScriptMessageHandler:self name:@"downfile"];
    
    
             // 创建设置对象
             WKPreferences *preference = [[WKPreferences alloc]init];
             // 设置字体大小(最小的字体大小)
             preference.minimumFontSize = 12;
             // 设置偏好设置对象
          //   wkWebConfig.preferences = preference;
             self.webView= [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];
     
//      WKDelegateController *delegateController = [[WKDelegateController alloc]init];
//      delegateController.delegate = self;
      
    
    
      [self.view addSubview:self.webView];

      UIEdgeInsets padding = UIEdgeInsetsMake(0, 0, 0, 0);
      [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
          make.edges.equalTo(self.view).with.insets(padding);
      }];
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0.8)];
      self.progressView.progressTintColor = [UIColor blueColor];
    
      //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
      self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
      [self.webView addSubview:self.progressView];
      [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
       self.webView.UIDelegate = self;
       self.webView.navigationDelegate = self;
       self.webView.allowsBackForwardNavigationGestures = NO;
       self.webView.allowsLinkPreview = YES;
    
//    _footView = [[UIView alloc]initWithFrame:CGRectMake(0,self.webView.bottom, kSCREEN_WIDTH,80)];
//    _footView.backgroundColor = [UIColor redColor];
//
//    self.webView.scrollView.contentInset = UIEdgeInsetsMake(0,0,0,0);
//
//    [self.webView.scrollView addSubview:_footView];

    [self getdata];
        
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    {
      self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
                                               initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                               style:UIBarButtonItemStyleDone
                                               target:self
                                               action:@selector(leftBarButtonClick)];
          
      }
}
- (void)leftBarButtonClick {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)getdata{
    [[ToastManager shardInstance]showSystemProgress:self.view];
    
    [[ApiManager ShardInstance]getDetailNoticeID:self.noticeID resultBlock:^(NSDictionary *data, NSError *error) {
        BaseModel *model = [BaseModel mj_objectWithKeyValues:data];
        if (model.code == 1) {
             [[ToastManager shardInstance]hideProgress:self.view];
            

            
//     党政之声
            if ([self.titleStr isEqualToString:@"党政之声"]) {
              self.headerString = @"<html><head><meta charset='utf-8'><title></title><style type='text/css'> .tittle{font-size: 25px;font-weight: bold;text-align: center;margin-top: 10px;}.tips{padding: 0 5px 0 5px;color: #b3aeae;font-size: 15px;display: flex;justify-content: space-between; align-items: center;margin-bottom: 20px;}.time{margin-right:10px;}.handle{ padding-left: 30px;margin-top:-60px;font-size: 20px;text-decoration: none; }.handle:visited {color: blue;text-decoration:none;}</style> </head> <body style='position:relative;box-sizing:border-box'><div style='position:absolute;left:50%;transform:translateX(-35%);top:0;'><div class='tittle'>";
            }else{
                self.headerString = @"<html><head><meta charset='utf-8'><title></title><style type='text/css'> .tittle{font-size: 25px;font-weight: bold;text-align: center;margin-top: 10px;}.tips{padding: 0 5px 0 5px;color: #b3aeae;font-size: 15px;display: flex;justify-content: space-between; align-items: center;margin-bottom: 20px;}.time{margin-right:10px;}.handle{ padding-left: 30px;margin-top:-60px;font-size: 20px;text-decoration: none; }.handle:visited {color: blue;text-decoration:none;}</style> </head> <body style='position:relative;box-sizing:border-box;width:100vw!important'><div style='position:absolute;left:50%;transform:translateX(-50%);top:0;width:100%!important'><div class='tittle'>";

            }
             
            NSString *title = [NSString stringWithFormat:@"%@",data[@"rs"][@"title"]];
            
            NSString *name = [NSString stringWithFormat:@"%@%@",@"</div><div class='tips'><div>",data[@"rs"][@"user_shortname"]];
            
            NSString *ttt = [NSString stringWithFormat:@"%@",data[@"rs"][@"create_time"]];
            NSString *time = [NSString stringWithFormat:@"%@%@%@",@"</div><div> <span class='time'>",[self ConvertStrToTime:ttt],@"</div></div>"];
           
            
//
//            NSString *moreStr = [NSString stringWithFormat:@"%@",data[@"rs"][@"more"]];
//            if ([moreStr isEqualToString:@"<null>"]) {
//                  self.footUrl = [NSString stringWithFormat:@"%@%@%@",@"<div class='test'><a class='handle' href="">",@"",@"</div></div>"];
//                return ;
//            }
//
//           // <div><inputtype="button"value="Call js confirm"onclick="downfile()"></div>
//               // self.footUrl = [NSString stringWithFormat:@"%@%@%@",@"<div class='test'><a class='handle' href="">",data[@"rs"][@"more"][@"files"][0][@"name"],@"</div></div>"];
//
//               self.footUrl = [NSString stringWithFormat:@"%@",@"<div><input type='button' value='call shareButton' onclick='downfile()'></div>"];
            
          //    self.fileUrl = [NSString stringWithFormat:@"%@%@",BaseImgUrl,data[@"rs"][@"more"][@"files"][0][@"url"]];

            
             // <div class='test'><a class='handle' href="">操作什么屌文档啥的</a></div>
             // [self.webView loadHTMLString:[NSString stringWithFormat:@"%@",data[@"rs"][@"content"]] baseURL:nil];
            NSString * aaa = @"</body></html>";
          // [self.webView loadHTMLString:[NSString stringWithFormat:@"%@%@%@%@%@%@%@",headerString,title,name,time,[NSString stringWithFormat:@"%@",data[@"rs"][@"content"]],self.footUrl,aaa] baseURL:nil];
            
           

         
             NSString *html = [NSString stringWithFormat:@"%@",data[@"rs"][@"content"]];
            
            //@"tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1"
            
            NSString *strUrl = [html stringByReplacingOccurrencesOfString: @"tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1" withString:@""];
       
            
             [self.webView loadHTMLString:[NSString stringWithFormat:@"%@%@%@%@%@%@",self.headerString,title,name,time,strUrl,aaa] baseURL:nil];
            
            
        }
        
    }];
    
    
}

//时间戳变为格式时间
- (NSString *)ConvertStrToTime:(NSString *)timeStr

{
    
    long long time=[timeStr longLongValue];
    //    如果服务器返回的是13位字符串，需要除以1000，否则显示不正确(13位其实代表的是毫秒，需要除以1000)
    //    long long time=[timeStr longLongValue] / 1000;
    
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString*timeString=[formatter stringFromDate:date];
    
    return timeString;
    
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    // [self endRefresh];
    
    if ([self.progressView isDescendantOfView:self.webView]) {
        self.progressView.hidden = NO;
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([self.progressView isDescendantOfView:self.webView]) {
        if ([keyPath isEqualToString:@"estimatedProgress"]) {
            self.progressView.progress = self.webView.estimatedProgress;
            if (self.progressView.progress == 1) {
                /*
                 *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
                 *动画时长0.25s，延时0.3s后开始动画
                 *动画结束后将progressView隐藏
                 */
                
                WS(weakSelf);
                [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                    weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
                } completion:^(BOOL finished) {
                    weakSelf.progressView.hidden = YES;
                    
                }];
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}

- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    //message.body传值的内容。
    //前端需要用 window.webkit.messageHandlers.注册的方法名.postMessage({body:传输的数据} 来给native发送消息
    //    window.webkit.messageHandlers.refreshApp.postMessage({body: 'hello world!'});
    if ([message.name isEqualToString:@"downfile"]) {
        NSLog(@"%@",message.body);
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
